//
//  HTClearCachFile.m
//  HeartTravel
//
//  Created by lanou on 15/11/3.
//  Copyright © 2015年 陈文杰. All rights reserved.
//

#import "HTClearCachFile.h"

@implementation HTClearCachFile

//计算当个文件大小
- (CGFloat)fileSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:path]) {
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        
        return size;
    }
    
    return 0;
}

//计算目录大小(cachs 文件夹下的数据和缓存的图片)

- (CGFloat)folderSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:path]) {
        return 0;
    }
    
    NSEnumerator *childFilesEnumerator = [[fileManager subpathsAtPath:path] objectEnumerator];
    NSString *fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil ) {
        NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    
    folderSize = folderSize/1024.0 /1024.0 + [[SDImageCache sharedImageCache] getSize] /1024.0 /1024.0;
    return folderSize;
}

//显示缓存

- (CGFloat)shouCachs
{
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(13, 1, 1)firstObject];
    
    return [self folderSizeAtPath:cachPath];
    
}

//清理缓存

- (void)clearCadchs
{
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(13, 1, 1)lastObject];
    
    NSArray *files = [manager subpathsAtPath:cachPath];
    
     NSLog(@"files:%lu",(unsigned long)[files count]);
    
    for (NSString *p  in files) {
        NSError *error;
        
        NSString *path = [cachPath stringByAppendingPathComponent:p];
        
        if ([manager fileExistsAtPath:path]) {
            [manager removeItemAtPath:path error:&error];
        }
    }
    
    [[SDImageCache sharedImageCache] cleanDisk];
    
    [self performSelectorOnMainThread:@selector(clearCachSueecss) withObject:nil waitUntilDone:YES];
}

- (void)clearCachSueecss
{
    NSLog(@"清理成功");
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"缓存清理完毕" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}



@end
